//
//  oldVoiceView.m
//  laonianbang
//
//  Created by 勇拓 李 on 17/10/18.
//  Copyright © 2017年 zaiyou. All rights reserved.
//

#import "oldVoiceView.h"
#import "oldVoiceManager.h"

@interface oldVoiceView()<AVAudioPlayerDelegate>
{
    BOOL isplay;
}
@property (nonatomic ,strong) AVAudioPlayer *player;
@property (nonatomic ,strong) AVPlayerItem *playerItem;
@property (nonatomic, strong)NSString *url;
@property (nonatomic, strong)UIActivityIndicatorView *hud;

@property (weak, nonatomic) IBOutlet UIButton *btn_play;
@property (weak, nonatomic) IBOutlet UILabel *label_time;
@property (weak, nonatomic) IBOutlet UIImageView *img_voice;
@property (strong, nonatomic)NSTimer *voice_timer;
@property (assign, nonatomic)NSUInteger index;

@end

NSString *const AVPLAYER_STOP_NOTICATION = @"AVPLAYER_STOP_NOTICATION";

@implementation oldVoiceView

- (void)awakeFromNib
{
    [super awakeFromNib];
    _btn_play.layer.cornerRadius = 3.f;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(otherPlayerPlayed:) name:AVPLAYER_STOP_NOTICATION object:_url];
    [_btn_play addTarget:self action:@selector(btn_touched:) forControlEvents:UIControlEventTouchDown];
}

- (UIActivityIndicatorView *)hud
{
    if (!_hud) {
        _hud = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(12, 11, 24, 24)];
        //    _hud.center = self.center;
        [_hud setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        [_hud setBackgroundColor:[UIColor clearColor]];
    }
    
    return _hud;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initUrl:(NSString *)url
{
    self.url = url;
    [self initPlayer:_url];
    _index = 0;
}

- (void)beginPlay:(NSString *)url
{
    WeakSelf
    [self hudBegin];
    [oldVoice getVoiceUrl:url block:^(NSString *newurl) {
        [weakSelf hudStop];
        [weakSelf initUrl:newurl];
    }];
}

- (void)removeView
{
    self.url = nil;
    [self closeTimer];
    [self removeFromSuperview];
}

- (void)beginWithRecord
{
    [self initUrl:[oldVoice getSavePath]];
}

#pragma mark -通知
- (void)otherPlayerPlayed:(NSNotification*) notification
{
    if (notification.object != _url) {
        isplay = NO;
        [self stop];
    }
}

#pragma mark - hud
- (void)hudBegin
{
    [self addSubview:self.hud];
    [self.hud startAnimating];
    _img_voice.hidden = YES;
    _btn_play.userInteractionEnabled = NO;
}

- (void)hudStop
{
    [_hud stopAnimating];
    [_hud removeFromSuperview];
    _img_voice.hidden = NO;
    _btn_play.userInteractionEnabled = YES;
}

#pragma mark -方法

- (void)btn_touched:(id)sender
{
    isplay = !isplay;
    if (isplay) {
        [self play];
    }
    else
    {
        [self stop];
    }
}

- (void)play
{
    [self startTimer];
    
    if (![self.player isPlaying]) {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        NSError *err = nil;
        [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
        [self.player play];
    }
}

- (void)stop
{
    [self.player stop];
    [self closeTimer];
}

- (void)closeTimer
{
    if (_voice_timer) {
        if ([_voice_timer isValid]) {
            [_voice_timer invalidate];
        }
        _voice_timer = nil;
    }
}

- (void)startTimer
{
    self.voice_timer = [NSTimer timerWithTimeInterval:.3 target:self selector:@selector(changeVoiceImg) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_voice_timer forMode:NSRunLoopCommonModes];
}

- (void)changeVoiceImg
{
    _index++;
    if (3 == _index) {
        _index = 0;
    }
    switch (_index) {
        case 0:
            _img_voice.image = [UIImage imageNamed:@"语音播放大"];
            break;
        case 1:
            _img_voice.image = [UIImage imageNamed:@"语音播放中"];
            break;
        default:
            _img_voice.image = [UIImage imageNamed:@"语音播放小"];
            break;
    }
}

#pragma mark player
- (void)initPlayer:(NSString *)urlPath
{
    NSURL *url = [NSURL URLWithString:urlPath];
    
    NSError *error = nil;
    //初始化播放器，注意这里的Url参数只能时文件路径，不支持HTTP Url
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    //设置播放器属性
    _player.numberOfLoops = 0;//设置为0不循环
    _player.delegate =  self;
    [_player prepareToPlay];//加载音频文件到缓存
    
    NSInteger time = _player.duration;
    _label_time.text = [NSString stringWithFormat:@"%ld''", (long)time];
    
    if(error){
        NSLog(@"初始化播放器过程发生错误,错误信息:%@",error.localizedDescription);
        return;
    }
}

#pragma mark - 播放器代理方法
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@"音乐播放完成...");
    _img_voice.image = [UIImage imageNamed:@"语音播放大"];
    isplay = NO;
    [self closeTimer];
}

@end
